<?php

class Admin_GalleryItemController extends Zend_Rest_Controller
{	
	public static function getPath(){return Admin_Model_GalleryItem::getPath();}
	public static function getTmpPath(){return Admin_Model_GalleryItem::getTmpPath();}	

    public function init(){
        parent::init();
    }

    public function indexAction(){
        $subaction = $this->_request->getParam('subaction',0);
        if ($subaction!==0) return $this->_processSubAction($subaction);
        //subaction
		echo "index";
    	exit;
    }
    private function _processSubAction($subaction){
        if ($subaction=='paste') return $this->pasteSubAction();
        throw new Zend_Exception("Sub Action ".$subaction." was not found");
    }
    public function pasteSubAction(){
        $form = new Admin_Form_GalleryItemPaste();
        $data = $this->_request->getParams();
        if (!$form->isValid($data))
            throw new Zend_Exception("Incorrect params");
        $data = $form->getValidValues($data);
        $mapper = new Admin_Model_GalleryItemMapper();
        $imgSrc = $mapper->find($data['SrcId'],$data['SrcSizeId']);
        $imgDst = $mapper->find($data['DstId'],$data['DstSizeId']);
        if ((null==$imgSrc) || (null==$imgDst))
            throw new Zend_Exception("Can't find source and/or destination images");
        $old_file = $imgDst->getFileName();
        $imgDst->setWidth($imgSrc->getWidth())->setHeight($imgSrc->getHeight())->setExt($imgSrc->getExt());
        $mapper->save($imgDst);
        unlink(self::getPath().$old_file);
        copy(self::getPath().$imgSrc->getFileName(),self::getPath().$imgDst->getFileName());
        $this->_helper->json(array('success'=>true));
    }
    
    public function getAction()
    {
    	$req = $this->getRequest();
    	$gi = new Admin_Model_GalleryItemMapper();
    	$result = null;
    	$includeSizeName = $req->getParam('sizeName',0);
    	
    	if((($id = (int)$req->getParam('id',0))>0) &&
    		(($sizeId = (int)$req->getParam('sizeId',0))>0)
    		)
    	{
    		$result = $gi->find($id,$sizeId);
		}
		elseif (($id>0) && ($sizeId==0))
		{
			$result = $gi->findAllImageSizes($id,$includeSizeName);
		}
    	$this->_helper->json ( array('data'=>$result) ); //для extjs
    }
     
    public function deleteAction()
    {
    	
    }
    
    public function postAction()
    {
    	$form =new Admin_Form_GalleryItemUpload();
      	if ($form->isValid($this->getRequest()->getParams())) {
      		$fi = $form->newfile->getFileInfo();
      		if ($form->newfile->receive()){
     			$location = $form->newfile->getFileName();
     			list($width, $height) = getimagesize($location);
     			$info = pathinfo($fi['newfile']['name']);
     			$m2 = new Admin_Model_GalleryItemMapper();
     			$path = Admin_GalleryItemController::getPath();
     			
     			if ((null==($Id=$form->getValue('Id')))
     				|| (null==($SizeId=$form->getValue('SizeId'))))
     			{     			
	     			$m1 = new Admin_Model_GallerySizesMapper();
	     			$sizes = $m1->fetchAll();
	     			if (count($sizes)==0)
	     				throw new Zend_Exception('Не заданы размеры для картинок');
	     			
	     			$gi = new Admin_Model_GalleryItem();
	     			$gi	->setSizeId($sizes[0]->getId())
	     				->setAlt($form->getValue('alt'))
	     				->setTitle($form->getValue('title'))
	     				->setWidth($width)
	     				->setHeight($height)
	     				->setExt($info['extension'])
	     				->setOrder(0);
	     			
	     			$newId = $m2->save($gi);
	     			$gi->setId($newId['Id']);
	     			$images = array($gi);
	     			
	     			foreach($sizes as $size){
	     				if (($size->getWidth()>0) && ($size->getHeight()>0)){ 
	     					list($width,$height) = Nippy_Image::ResizeImage(	$location, 
		     											$info['extension'], 
		     											$size->getWidth(), 
		     											$size->getHeight(),
		     											$path.$newId['Id'].'_'.$size->getId().'_%wx%h.'.$info['extension']
		     											);
		     				$gi = new Admin_Model_GalleryItem($gi->toArray());
		     				$gi	->setSizeId($size->getId())
		     					->setWidth($width)
	     						->setHeight($height);
		     				$m2->save($gi, true);
		     				$images[]=$gi;
	     				}
	     				else
	     					copy($location, $path."{$newId['Id']}_{$size->getId()}_{$width}x{$height}.{$info['extension']}");
	     			}
     			}
     			else{
     				$m2->delete($form->getValue('Id'),$form->getValue('SizeId'),false,true);
     				$gi = new Admin_Model_GalleryItem();
     				$gi	->setId($form->getValue('Id'))
     					->setSizeId($form->getValue('SizeId'))
	     				->setAlt($form->getValue('alt'))
	     				->setTitle($form->getValue('title'))
	     				->setWidth($width)
	     				->setHeight($height)
	     				->setExt($info['extension']);
	     			$m2->save($gi,false,array('Alt'=>'', 'Title'=>'','Width'=>'','Height'=>'','Ext'=>''));
	     			$images = array($gi);
	     			copy($location, $path."{$gi->getId()}_{$gi->getSizeId()}_{$width}x{$height}.{$gi->getExt()}");
     			}
     			if (unlink($location)) 
	     			$result = array('success'=>true, 'images'=>$images);
	     		else $result = array('success'=>false, 'msg'=> 'Невозможно переименовать файл');
      		}
      		else $result = array('success'=>false, 'msg'=>'Невозможно получить файл');		
      	}
      	else $result = array('success'=>false, 'msg'=> 'В полях формы заданы неверные значения');
      	$this->view->result = $result;
      	$this->_helper->layout()->disableLayout();
      	/* Нельзя заменять на $this->_helper->json($result);
         * потому что должно быть Content-Type: text/html
         * а в json там другое
         */
    }
    
    public function putAction()
    {
    	$request = $this->getRequest();
    	$result = Zend_Json::decode ( $request->getRawBody () );
		$id = explode ( '-', $request->getParam ( 'id', "0-0" ));
		$Id = (int)$id[0];
    	$SizeId = (int)$id[1];
		
		$filterChain = new Zend_Filter ( );
		$filterChain->addFilter ( new Zend_Filter_StripTags ( ) )
                ->addFilter ( new Zend_Filter_StringTrim ( ) )
                ->addFilter ( new Zend_Filter_HtmlEntities ( ) );
		if (($Id>0) && ($SizeId>0))
    	{
    		$item = new Admin_Model_GalleryItem();
    		$item->setId($Id);
    		$item->setSizeId($SizeId);
    		$fields = array();
    		if (isset($result['data']['Alt'])){
    			$item->setAlt($filterChain->filter($result['data']['Alt']));
    			$fields['Alt']='';	
    		}
    		if (isset($result['data']['Title'])){
    			$item->setTitle($filterChain->filter($result['data']['Title']));
    			$fields['Title']='';	
    		}
    		if (count($fields)>0){
    			$m = new Admin_Model_GalleryItemMapper();
	    		$m->save($item,false,$fields);
	    		$result = array('success'=>true, 'msg'=>'Информация сохранена');
    		}
    		else
    			$result = array('success'=>true, 'msg'=>'Информация несохранена - нет изменений');
    	}
    	else
    		$result = array('success'=>false, 'msg'=>'Не установлен Id и/или SizeId');
	    $this->_helper->json($result);
    }
}
